// 设置为全局变量
window.API_CONFIG = {
    API_HOST: 'http://erpapi.hkpublicholiday.com',
    BASE_URL: 'http://erp.hkpublicholiday.com',
    USER_KEY: 'erp_user',
    TOKEN_KEY: 'erp_token'
};

// API 请求工具，设置为全局变量
window.apiClient = axios.create({
    baseURL: API_CONFIG.API_HOST,
    timeout: 30000,
    headers: {
        'Accept': 'application/json'
    }
});

// 请求拦截器
window.apiClient.interceptors.request.use(
    (config) => {
        // 打印请求配置
        console.log('Request details:', {
            url: config.url,
            method: config.method,
            headers: config.headers,
            data: config.data
        });
        
        const userStr = localStorage.getItem(API_CONFIG.USER_KEY);
        if (userStr) {
            try {
                const user = JSON.parse(userStr);
                if (user.access_token) {
                    const authHeader = `Bearer ${user.access_token}`;
                    config.headers['Authorization'] = authHeader;
                    
                    // 打印每个请求的认证信息
                    console.log('Request auth info:', {
                        url: config.url,
                        token_preview: user.access_token.substring(0, 20) + '...',
                        full_header: authHeader
                    });
                }
            } catch (e) {
                console.error('Parse user data error:', e);
            }
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
window.apiClient.interceptors.response.use(
    (response) => {
        console.log('Response success:', {
            url: response.config.url,
            status: response.status,
            headers: response.headers
        });
        return response;
    },
    async (error) => {
        console.error('API Error:', {
            url: error.config?.url,
            status: error.response?.status,
            data: error.response?.data,
            headers: error.response?.headers
        });
        
        if (error.response?.status === 401) {
            console.error('Authentication failed');
            // 清除无效的 token
            localStorage.removeItem(API_CONFIG.USER_KEY);
            localStorage.removeItem(API_CONFIG.TOKEN_KEY);
        }
        
        return Promise.reject(error);
    }
); 